import axios from 'axios'
import {addRequestPending, removeRequestPending,} from '@/utils/cacelRequest'
import {ElMessage} from "element-plus";
import router from "@/router";

const baseUrl = process.env.NODE_ENV === 'development' ? '/api/' : window.origin + '/admin-domain/'
// 创建axios实例

const service = axios.create({
    timeout: 30000, // 请求超时时间ss
    baseURL: baseUrl
})
const codeMessage = {
    403: '当前账户无此操作权限，请联系管理员',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作',
    500: '服务器发生错误，请稍后再试',
    502: '网关错误',
    503: '服务不可用，服务器暂时过载或维护',
    504: '网关超时',
    1000: '连接超时',
    1001: '登录超时,请重新登录',
};
// request拦截器
service.interceptors.request.use(config => {
    const token = sessionStorage.getItem('token')
    if (token) {
        config.headers.token = token
    }
    addRequestPending(config)
    return config
}, error => {
    Promise.reject(error)
})
// response拦截器
service.interceptors.response.use(
    async response => {
        const {data, config} = response
        const code = data.code
        removeRequestPending(config)
        if (typeof code !== 'undefined') {
            if (code !== 200) {
                ElMessage({
                    type: 'error',
                    duration: 6000,
                    message: data.message
                })
                if (code === 502) {
                    router.push('/login')
                }
            }
        }
        return response.data
    },
    error => {
        let code
        try {
            code = error.response.status
        } catch {
            //请求超时
            if (error.code === 'ECONNABORTED') {
                code = 1000
            }
        }
        if (code) {
            ElMessage({
                message: codeMessage[code] ? code + ' ' + codeMessage[code] : error,
                type: 'error',
                duration: 6000,
            })
        }
        removeRequestPending(error.config || {})
        console.error(error)
        // 接口错误返回错误码
        return {code: 0}
    }
)

export default service
